import bpy
from bpy import msgbus
from bpy.types import Scene, Object, Material, ParticleSettings, LayerObjects
from bpy.props import PointerProperty
# from .addon.install_pillow import install_pillow, uninstall_pillow
from bpy.utils import register_class, unregister_class, previews
from bpy.app.handlers import persistent
from .addon.naming import FluidLabNaming

from .addon import ADDON_PREFERENCES
from .addon import icons
from .properties import PROPERTIES
from .panels import PANELS
from .operators import OPERATORS

from .properties.main.main_pointers_props import FluidLabPointers
from .properties.data_props.data_props_objects import FLUIDLAB_DATA_Object
from .properties.data_props.data_props_material import FLUIDLAB_DATA_Material
from .properties.data_props.data_props_psettings import FLUIDLAB_DATA_ParticleSettings

from .properties.shading.props_shading import FluidLab_PG_Shading
from .libs.functions.basics import append_function_unique


bl_info = {
    "name": "FluidLab",
    "author": "RBDLab Studio",
    "description": "FluidLab Addon vfxMed",
    "blender": (4, 1, 1),
    "version": (1, 1, 0),
    "doc_url": "https://sites.google.com/view/fluidlabuserguide/home",
    "category": "Physics"
}


def selection_event(*args):
    
    """
        This function handles the event when the selection changes.
        It updates the active fluid group and emitter index based on the current active object.
    """
    
    context = bpy.context
    active_object = context.active_object
    if not active_object:
        return
    
    if FluidLabNaming.EMITTER_OB not in active_object:
        return

    scene = context.scene
    fluidlab = scene.fluidlab
    lists = fluidlab.lists 
    fluid_groups = lists.fluid_groups
    
    if not fluid_groups.is_void:

        all_groups = fluid_groups.get_all_items

        for group_idx, group in enumerate(all_groups):
            
            emitters_list = group.emitters
            if emitters_list.is_void:
                continue

            emitters = emitters_list.get_all_emitters
            if active_object not in emitters:
                continue

            fluid_groups.active = group_idx
            emitters_list.active = emitters.index(active_object)
            break


def watch_selection_event():
    """ Subscribes to the selection change event if not already subscribed. """
    msgbus.subscribe_rna(
        key=(LayerObjects, 'active'),
        owner=bpy,
        args=(),
        notify=selection_event
    )


@persistent
def fluidlab_load_post_handler(dummy):
    """ Handler that runs after loading a new scene. """
    watch_selection_event()


def register():

    for cls in ADDON_PREFERENCES:
        register_class(cls)

    if hasattr(icons, "register"):
        icons.register()

    for cls in PROPERTIES:
        register_class(cls)

    Scene.fluidlab = PointerProperty(type=FluidLabPointers)
    Object.fluidlab = PointerProperty(type=FLUIDLAB_DATA_Object)
    Material.fluidlab = PointerProperty(type=FLUIDLAB_DATA_Material)
    ParticleSettings.fluidlab = PointerProperty(type=FLUIDLAB_DATA_ParticleSettings)

    for cls in PANELS:
        register_class(cls)

    for op in OPERATORS:
        register_class(op)

    # NOTA: (Esto lo tenía puesto con la esperanza de que la galería de thumbnails detectase lo del BIP -> pillow, pero no lo pilla)
    # Si no estuviera instalado Pillow, lo instalamos: 
    # install_pillow()

    append_function_unique(bpy.app.handlers.load_post, fluidlab_load_post_handler)



def unregister():

    if hasattr(icons, "unregister"):
        icons.unregister()

    del Scene.fluidlab
    del Object.fluidlab
    del Material.fluidlab
    del ParticleSettings.fluidlab

    for cls in PANELS:
        unregister_class(cls)

    for cls in PROPERTIES:
        unregister_class(cls)

    for op in OPERATORS:
        unregister_class(op)
    
    for cls in ADDON_PREFERENCES:
        unregister_class(cls)

    preview_collection = FluidLab_PG_Shading.thumbs_coll
    if preview_collection:
        for name, pcoll in preview_collection.items():
            #print(f"Eliminando colección de vista previa: {name}")
            previews.remove(pcoll)
        preview_collection.clear()
    
    # NOTA: (Esto lo tenía puesto con la esperanza de que la galería de thumbnails detectase lo del BIP -> pillow, pero no lo pilla)
    # Desinstalamos Pillow:
    # uninstall_pillow()

    bpy.app.handlers.load_post.remove(fluidlab_load_post_handler)